/*
Copyright (c) 2009 Blue Kai, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
Components.utils.import('resource://gre/modules/XPCOMUtils.jsm');

const PREFS_BRANCH = 'extensions.ahi.';
const REGISTRY_BOOTSTRAP_URI='chrome://ahi/content/registry.json';
const DB_FILENAME = 'ahi.sqlite';
const TABLE_NAME = 'permanent_cookies';
const MIN_ACCEPTABLE_EXPIRATION_WINDOW = 20 * 365 * 24 * 3660; // 20 years
const LL_MAXINT = 9223372036854775807;
const EXTENSION_ID = 'optoutprotector@networkadvertising.org';

function BK () {
    this.wrappedJSObject = this;
}

var log = (function () {
    var _ = {
        inited: false,
        enabled: false,
        json: null
    };
    
    return function () {
        if (! _.inited) {
            _.inited = true;
            _.enabled = Components.classes['@mozilla.org/preferences-service;1']
                            .getService(Components.interfaces.nsIPrefService)
                            .getBranch(PREFS_BRANCH)
                            .getBoolPref('enableDebugging');
            _.json = Components.classes['@mozilla.org/dom/json;1']
                            .createInstance(Components.interfaces.nsIJSON);

        }
        if (_.enabled) {
            var msg = [];
            for (var i=0; i < arguments.length; i++) {
                var a = arguments[i];
                if (typeof a != 'string' && typeof a == 'object') {
                    a = _.json.encode(a);
                }
                msg.push(a);
            }
            dump('ahi: ' + msg.join(', ') + '\n');
        }
    };
})();

function cookieDesc (c) {
    if (c == null) {
        return "null";
    }
    return [ c.host, c.path, c.name, c.value, c.expiry, c.isSecure ? 'true' : 'false', c.isHttpOnly ? 'true' : 'false'].join(':');
}

function CookieStash (filename) {
    var _ = {    
        freshNewStash: false,
        
        execSqlStatement: function (sql, callback) {
            try {
                var file = Components.classes['@mozilla.org/file/directory_service;1']
                                .getService(Components.interfaces.nsIProperties)
                                .get('ProfD', Components.interfaces.nsIFile);
                file.append(filename);

                var storageService = Components.classes['@mozilla.org/storage/service;1']
                        .getService(Components.interfaces.mozIStorageService);
                var db = storageService.openDatabase(file);
                var wstmt = null;
                if (sql) {
                    wstmt = Components.classes['@mozilla.org/storage/statement-wrapper;1']
                               .createInstance(Components.interfaces.mozIStorageStatementWrapper);
                    wstmt.initialize(db.createStatement(sql));
                }
                var ret = callback(wstmt, db);
                if (wstmt) {
                    wstmt.reset();
                    wstmt.statement.finalize();
                }
                return ret;
            } catch (e) {
                log("Exception execing SQL\nsql: " + sql + "\n" + e + e.stack);
            }
        },
        
        init: function () {
            log('>>> INITIALIZING DATABASE >>>');
            _.execSqlStatement(null, function (stmt, db) {
               if (! db.tableExists(TABLE_NAME)) {
                   _.freshNewStash = true;
                   
                   var schema = 'host TEXT, path TEXT, name TEXT, value TEXT, expiry INTEGER, isSecure INTEGER, isHttpOnly INTEGER';
                   db.createTable(TABLE_NAME, schema);
                   log(DB_FILENAME + ': created table ' + TABLE_NAME);
               } else {
                   self.cullByExpiry(nowTimestamp());
                   self.all().forEach(function (c) {
                      log(TABLE_NAME + ': permanent cookie: ' + cookieDesc(c));
                   });
               }
            });
            log('<<< DATABASE INITIALIZED <<<');
        }
    };
    
    var self = {
        stash: function (cookie) {
            this.unstash(cookie);
            var sql = 'INSERT INTO "' + TABLE_NAME + '" (host, path, name, value, expiry, isSecure, isHttpOnly) VALUES (:host, :path, :name, :value, :expiry, :isSecure, :isHttpOnly)';
            _.execSqlStatement(sql, function (wstmt, db) {
               wstmt.params.host = cookie.host; 
               wstmt.params.path = cookie.path; 
               wstmt.params.name = cookie.name; 
               wstmt.params.value = cookie.value; 
               wstmt.params.expiry = cookie.expiry; 
               wstmt.params.isSecure = cookie.isSecure ? 1 : 0; 
               wstmt.params.isHttpOnly = cookie.isHttpOnly ? 1 : 0;
               wstmt.execute();
            });
            return cookie;
        },
    
        unstash: function (cookie) {
            var sql = 'DELETE FROM "' + TABLE_NAME + '" WHERE host = :host AND path = :path AND name = :name';
            _.execSqlStatement(sql, function (wstmt, db) {
               wstmt.params.host = cookie.host; 
               wstmt.params.path = cookie.path; 
               wstmt.params.name = cookie.name;
               wstmt.execute();
           });
           return cookie;
        },

        all: function () {
            var cookies = [];
            var sql = 'SELECT * FROM "' + TABLE_NAME + '" WHERE expiry > :expiry';
            _.execSqlStatement(sql, function (wstmt, db) {
                wstmt.params.expiry = nowTimestamp();
                while (wstmt.step()) {
                    cookies.push({
                        host: wstmt.row.host,
                        path: wstmt.row.path,
                        name: wstmt.row.name,
                        value: wstmt.row.value,
                        expiry: wstmt.row.expiry,
                        isSecure: wstmt.row.isSecure == 1,
                        isHttpOnly: wstmt.row.isHttpOnly == 1
                    });
                }
            });

           return cookies;
        },
        
        cullByExpiry: function (expiry) {
            if (expiry > LL_MAXINT) { return; }
            
            var sql = 'DELETE FROM "' + TABLE_NAME + '" WHERE expiry < :expiry';
            _.execSqlStatement(sql, function (wstmt, db) {
               wstmt.params.expiry = expiry;
               wstmt.execute();
           });
            
        },
        
        freshNewStash: function () {
            return _.freshNewStash;
        }
    };
    _.init();
    return self;
}

/**
 * General Approach
 *
 * Cleared -> reinstate all cookies
 * Delete -> delete the cookie
 * Deleted during the sanitization phase ("Clear Recent History" dialog) -> reinstate the cookie 
 * Added -> permanentize cookie
 *
 */
function CookieObserver (ahi) {
    var nativeJSON = Components.classes['@mozilla.org/dom/json;1']
                    .createInstance(Components.interfaces.nsIJSON);

    var protectDeletes = false;

    return {
        
        observe: function (subject, topic, data) {
            try {
                subject.QueryInterface(Components.interfaces.nsICookie2);
            } catch (e) {
            }
            log("=== Observed SUBJECT: " + cookieDesc(subject) + " | TOPIC: " + topic + " | DATA: " + data + " | protectDeletes:" + (protectDeletes ? 'true' : 'false'));
            
            if (topic == 'cookie-changed') {
                
                if (data == 'sanitize-pre') {
                    protectDeletes = true;

                } else if (data == 'sanitize-post') {
                    protectDeletes = false;
                    ahi.reinstateCookies();

                } else if (data == 'added' || data == 'changed' ) {
                    ahi.permanentizeCookie(subject);
                    ahi.reinstateCookies();

                } else if (data == 'cleared')  {
                    ahi.reinstateCookies();

                } else if (data == 'deleted') {
                    if (! protectDeletes) {
                        ahi.unpermanentizeCookie(subject);
                    }
                }
            }
        }
    };
}

function nowTimestamp () {
    return Math.floor((new Date()).getTime() / 1000);
}

BK.prototype = {
    classDescription: 'Ahi Opt Out Cookie Shield by BlueKai, Inc. XPCOM Component',
    classID: Components.ID('{adc5dcf2-6d68-4ad8-827b-e0a9e0cd849b}'),
    contractID: '@bluekai.com/ahi;1',
    QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsISupports]),

    started: false,
    
    /*** public functions ***/
    start: function () {
        if (this.started) { return; }
        this.started = true;
        this.ahi.init();
    },
    
    permanentLocalCookies: function () {
        
        return this.ahi.permanentLocalCookies();
    },
    
    companyForCookie: function (c) {
        return this.ahi.companyForCookie(c);
    },
    
    getRegistries: function () {
        return this.ahi.getRegistries();  
    },
    
    
    setRegistryUris: function (uris) {
        this.ahi.setRegistryUris(uris);
    },
    
    sawRegistryMessage: function (registryUri) {
        try {
        return this.ahi.sawRegistryMessage(registryUri);
    } catch (e) {
        log(e);
    }
    },
    
    anyCookiesPermanent: function (cookies) {
        var that = this;
        return cookies.filter(function (c) {
            return that.ahi.isPermanent(c);
        });
    },
    
    restoreDefaults: function (forUninstall) {
        this.ahi.restoreDefaults(forUninstall);        
    },
    
    /*** end public functions ***/
    
    ahi: {
    
        registry: [],
        registryNames: {},
        registryMessages: {},
    
        permanentCookies: null,

        prefs: null,
    
        cookieManager: null,
    
        observerService: null,
        
        inited: false,
        init: function () {
            try {
            if (this.inited) { return; }
            this.inited = true;
                        
            log(">>>>> INITIALIZING AHI >>>>>");

            this.prefs = Components.classes['@mozilla.org/preferences-service;1']
                            .getService(Components.interfaces.nsIPrefService)
                            .getBranch(PREFS_BRANCH);
            this.cookieManager = Components.classes['@mozilla.org/cookiemanager;1']
                                    .getService(Components.interfaces.nsICookieManager2);
            
            this.permanentCookies = CookieStash(DB_FILENAME);
            
            this.observerService = Components.classes['@mozilla.org/observer-service;1']
                .getService(Components.interfaces.nsIObserverService);
            this.observerService.addObserver(CookieObserver(this), 'cookie-changed', false);

            this.firstRun();
            
            this.initRegistry(false);
            
            if (this.permanentCookies.freshNewStash()) {
                this.processAllCookies();
            } else {
                this.cleanPermanentCookies();                
                this.reinstateCookies();
            }
            
        } catch (e) {
            log(e); 
        }
            log("<<<<< AHI INITIALIZED <<<<<");
        },
        
        firstRun: function () {

            var current;
            if (Components.classes["@mozilla.org/extensions/manager;1"]) { // pre 4.0
                var extensionManager = Components.classes["@mozilla.org/extensions/manager;1"]
                                    .getService(Components.interfaces.nsIExtensionManager);
                this.firstRunProper(extensionManager.getItemForID(EXTENSION_ID).version)

            } else { //post 4.0
                Components.utils.import("resource://gre/modules/AddonManager.jsm");
                var that = this;
                AddonManager.getAddonByID(EXTENSION_ID, function (addon) {
                    that.firstRunProper(addon.version); 
                });
                
            }
        },
        
        firstRunProper: function (current) {    
            var ver = -1, firstrun = true;            
            try {
                ver = this.prefs.getCharPref("version");
                firstrun = this.prefs.getBoolPref("firstrun");
            } catch (e) {
                //nothing
            } finally {
                log('ver: ' + ver + ' firstrun: ' + (firstrun ? 'true' : 'false'));

                if (firstrun) {
                    this.prefs.setBoolPref("firstrun", false);
                    this.prefs.setCharPref("version", current);

                    // Insert code for first run here        
                    if (this.prefs.prefHasUserValue('registryUpdateUris')) {
                        log('Clearing User Pref registryUpdateUris');
                        this.prefs.clearUserPref('registryUpdateUris');
                        this.initRegistry(true);
                        var that = this;
                        this.permanentCookies.all().forEach(function (c) {
                            that.permanentCookies.unstash(c);
                        });
                        log('refreshing protected cookies');
                        this.processAllCookies();
                    }

                    if (ver != current && !firstrun){ // !firstrun ensures that this section does not get loaded if its a first run.
                        this.prefs.setCharPref("version", current);

                        // Insert code if version is different here => upgrade
                    }
                }
            }
        },
        
        initRegistry: function (force) {
            log('>>> INITIALIZING REGISTRY >>>');
            
            var reg = this.fetchRegistry(force);
            this.registry = reg.registry;
            this.registryNames = reg.names;
            this.registryMessages = reg.messages;
            this.registry.forEach(function (e) {
                log('entry: ' + [e.company, e.host, e.path, e.name, e.value].join(':'));
            });

            this.observerService.notifyObservers(null, 'ahi-registry', 'registry-changed');

            log('<<< REGISTRY INITIALIZED <<<');
        
        },
        
        fetchRegistry: function (force) {
            var nativeJSON = Components.classes['@mozilla.org/dom/json;1']
                                .createInstance(Components.interfaces.nsIJSON);

            // fetches JSON from uri, and updates preferences
            var fetch = function (uri) {
                var r = null;
                var req = Components.classes['@mozilla.org/xmlextras/xmlhttprequest;1']
                                .createInstance(Components.interfaces.nsIXMLHttpRequest);
                var that = this;
                req.onload = function () {
                    var nativeJSON = Components.classes['@mozilla.org/dom/json;1']
                        .createInstance(Components.interfaces.nsIJSON);
                    r = req.responseText;
                };
                req.onerror = function () {
                    log('* Error fetching ' + uri);
                };
                req.open("GET", uri, false /* async */);
                try {
                    req.send(null);
                } catch (e) {
                    log('error fetching uri ' + uri);
                }
                var ret = null;
                try {
                    ret = r ? nativeJSON.decode(r) : null;
                } catch (e) {
                    log('error parsing json from ' + uri + ":\n" + r);
                }
                
                return ret;
            };

            var rawReg = null; // uri: uri-specific-registry key-value pairs
            var lastUpdated = this.prefs.getIntPref('registryLastUpdated');
            if (force || lastUpdated == 0 || lastUpdated + this.prefs.getIntPref('registryUpdateFrequency') < nowTimestamp()) {
                if (lastUpdated == 0) {
                    rawReg = { REGISTRY_BOOTSTRAP_URI: fetch(REGISTRY_BOOTSTRAP_URI) };
                } else {
                    rawReg = nativeJSON.decode(this.prefs.getCharPref('registry'));
                }
                var success = false;
                var uris = nativeJSON.decode(this.prefs.getCharPref('registryUpdateUris'));
                uris.forEach(function (uri) {
                    var r = fetch(uri);
                    if (r) {
                        rawReg[uri] = r;
                        delete rawReg[REGISTRY_BOOTSTRAP_URI]; // delete the bootstrap data if we get successfully fetch it
                        success = true;
                    }
                });

                if (success) {
                    this.prefs.setCharPref('registry', nativeJSON.encode(rawReg));
                    this.prefs.setIntPref('registryLastUpdated', nowTimestamp());
                }

            } else {
                rawReg = nativeJSON.decode(this.prefs.getCharPref('registry'));
            }

            // combine the registries
            var reg = [];
            var names = {};
            var messages = {};
            for (var uri in rawReg) {
                if (rawReg.hasOwnProperty(uri)) {
                    var r = rawReg[uri];
                     // add version specific logic here
                    if (r['version'] == 1) {
                        reg = reg.concat(r['registry']);
                        if (r['message']) {
                            messages[uri] = r['message'];
                        }
                        if (r['name']) {
                            names[uri] = r['name'];
                        }
                    } else {
                        log('Unsupported registry version ' + r['version'] + ': ' + uri);
                    }
                }
            }
            return { registry: reg, names: names, messages: messages };
        },
    
        cleanPermanentCookies: function () {
            var that = this;
            var cookiesToRemove = this.permanentCookies.all().filter(function (c) {
               return that.isPermanent(c) === false;
            });
            cookiesToRemove.forEach(function (c) {
               that.permanentCookies.unstash(c);
            });
            
        },
        
        fixupCookie: function (cookie) {
            var minExpiry = nowTimestamp() + MIN_ACCEPTABLE_EXPIRATION_WINDOW;
            if (cookie.expiry > LL_MAXINT || cookie.expiry < minExpiry) {
                log('Adjusting ' + cookieDesc(cookie) + ' expiry to ' + minExpiry);
                var newCookie = {
                    host: cookie.host,
                    path: cookie.path,
                    name: cookie.name,
                    value: cookie.value,
                    expiry: minExpiry,
                    isSecure: cookie.isSecure,
                    isHttpOnly: cookie.isHttpOnly
                };
                cookie = newCookie;
                this.setCookie(cookie);
            } else {
                log('Not adjusting: ' + cookie.expiry + ' < ' + minExpiry);
            }
            return cookie;
        },
        
        processAllCookies: function () {
            var cookieEnum = this.cookieManager.enumerator;
            while (cookieEnum.hasMoreElements()) {
                var c = cookieEnum.getNext();
                this.permanentizeCookie(c);
            }
        },
        
        permanentizeCookie: function (cookie) {
            
            cookie.QueryInterface(Components.interfaces.nsICookie2);
            var logString = 'Permanent? [' + cookieDesc(cookie) + ']: ';
            if (this.isPermanent(cookie)) {
                cookie = this.fixupCookie(cookie);
                this.permanentCookies.stash(cookie);
                logString += 'TRUE';
            } else {
                logString += 'FALSE';
            }
            log(logString);
            this.observerService.notifyObservers(null, 'cookie-changed', 'permanent-cookies-changed');

        },
        
        isPermanent: function (cookie) {
            return this.registry.some(function (c) {
                return c.host == cookie.host && c.path == cookie.path && c.name == cookie.name && c.value == cookie.value;
            });
        },
    
        unpermanentizeCookie: function (cookie) {
            try {
                cookie.QueryInterface(Components.interfaces.nsICookie2);
            } catch (e) {
                // do nothing
            }
            this.permanentCookies.unstash(cookie);
            this.observerService.notifyObservers(null, 'cookie-changed', 'permanent-cookies-changed');
            log("===> unpermanentized: " + cookieDesc(cookie));
        },

        setCookie: function (c) {
            this.cookieManager.add(c.host, c.path, c.name, c.value, c.isSecure, c.isHttpOnly, c.isSession, c.expiry);
            return c;
        },
        
        _reinstating: false, // prevent snowballs since reinstateCookies() generates 'changed' events 
        reinstateCookies: function () {

            if (this._reinstating) {
                log("(already reinstating)")
                return;
            }

            try {
                this._reinstating = true;
                var timer = Components.classes["@mozilla.org/timer;1"]
                    .createInstance(Components.interfaces.nsITimer);
            
                var self = this;
                timer.initWithCallback(function () {
                    try {                
                        log('>>>>> REINSTATING COOKIES >>>>>');
                        if (Components.classes['@mozilla.org/preferences-service;1']
                            .getService(Components.interfaces.nsIPrefBranch)
                            .getIntPref('network.cookie.cookieBehavior') !== 0) { return; }
                        var now = nowTimestamp();
                        self.permanentCookies.all().forEach(function (c) {
                            if (c.expiry > now) {
                                self.setCookie(c);
                                log("reinstated " + cookieDesc(c));
                            } else {
                                log("not reinstated" + cookieDesc(c));
                            }
                        }, this);

                        self.observerService.notifyObservers(null, 'cookie-changed', 'permanent-cookies-changed');

                    } catch (e) {
                        log(e);

                    } finally {
                        timer.initWithCallback(function () { // not sure why this is needed, but it seems to unstuck some timing issue on large pages with lotsa delayed cookies
                            self._reinstating = false;
                            log('<<<<< COOKIES REINSTATED <<<<<');
                        }, 10, 
                        Components.interfaces.nsITimer.TYPE_ONE_SHOT);
                    }
                }, 500, 
                Components.interfaces.nsITimer.TYPE_ONE_SHOT);
            } catch (e) {
                this._reinstating = false;
                log(e);
            }
        },

        permanentLocalCookies: function () {
            var copy = [];
            this.permanentCookies.all().forEach(function (cookie) {
                copy.push( {
                    host: cookie.host,
                    path: cookie.path,
                    name: cookie.name,
                    value: cookie.value,
                    expiry: cookie.expiry,
                    isSecure: cookie.isSecure,
                    isHttpOnly: cookie.isHttpOnly                    
                });
            });
            
            return copy;
        },

        companyForCookie: function (c) {
            for (var i = 0; i < this.registry.length; i++) {
                var r = this.registry[i];
                if (r.host == c.host && r.path == c.path && r.name == c.name && r.value == c.value) {
                    return r.company;
                } 
            }
            
            return null;
        },
        
        getRegistries: function () {
            var nativeJSON = Components.classes['@mozilla.org/dom/json;1']
                                .createInstance(Components.interfaces.nsIJSON);
            var reg = nativeJSON.decode(this.prefs.getCharPref('registryUpdateUris'));
            var registries = reg.map(function(uri) {
                var msg = this.getRegistryMessage(uri);
                return { uri: uri,
                        name: this.getRegistryName(uri),
                        messageUri: msg.uri,
                        messageUpdated: msg.updated }; 
            }, this);

            return registries;
        },

        setRegistryUris: function (uris) {
            var nativeJSON = Components.classes['@mozilla.org/dom/json;1']
                                .createInstance(Components.interfaces.nsIJSON);

            try {
                this.prefs.setCharPref('registryUpdateUris', nativeJSON.encode(uris));
                this.prefs.setCharPref('registry', '{}');
                log('Setting registries: ' + nativeJSON.encode(uris));
            } catch (e) {
                log('error setting registry uris ' + uris + ':' + e + e.stack);
            }
        
            this.evaluateNewRegistries();            
        },

        evaluateNewRegistries: function () {
            this.initRegistry(true);
            // refresh the protected cookies since we've change the registries
            log('flushing protected cookies');
            var that = this;
            this.permanentCookies.all().forEach(function (c) {
               that.permanentCookies.unstash(c);
            });
            log('refreshing protected cookies');
            this.processAllCookies();
            
        },
        
        getRegistryName: function (uri) {
            return this.registryNames[uri];
        },
        
        getRegistryMessage: function (uri) {
            var msgUri = null;
            var updated = true;
            
            var msg = this.registryMessages[uri];
            if (msg) {
                var nativeJSON = Components.classes['@mozilla.org/dom/json;1']
                    .createInstance(Components.interfaces.nsIJSON);

                msgUri = msg.uri;

                var seen = nativeJSON.decode(this.prefs.getCharPref('registryMessagesSeen'));
                if (seen[uri]) {
                    try {
                        if (parseInt(seen[uri]) >= parseInt(msg.version)) {
                            updated = false;
                        }
                    } catch (e) {
                        log(e);
                    }
                } 
            }

            return { uri: msgUri,
                     updated: updated };
        },

        sawRegistryMessage: function (uri) {
            var nativeJSON = Components.classes['@mozilla.org/dom/json;1']
                .createInstance(Components.interfaces.nsIJSON);

            var msg = this.registryMessages[uri];
            if (msg) {
                var seen = nativeJSON.decode(this.prefs.getCharPref('registryMessagesSeen'));
                seen[uri] = '' + msg.version;
                this.prefs.setCharPref('registryMessagesSeen', nativeJSON.encode(seen));        
            }
        },
        
        restoreDefaults: function (forUninstall) {
            try {
                var prefsToClear = ['registry', 'registryLastUpdated', 'registryMessagesSeen', 'registryUpdateUris'];
                if (forUninstall) {
                    prefsToClear.push('firstRun');
                    prefsToClear.push('version');
                }
                prefsToClear.forEach(function (prefName) {
                    try {
                        if (this.prefs.prefHasUserValue(prefName)) {
                            log('Clearing User Pref ' + prefName);
                            this.prefs.clearUserPref(prefName);
                        }
                    } catch (e) {
                        log(e);
                    }
                }, this);

                if (! forUninstall) {
                    this.evaluateNewRegistries();
                }
            } catch (e) {
                log(e);
            }
        }

    }
            
};

var components = [ BK ];

if (XPCOMUtils.generateNSGetFactory) {
    var NSGetFactory = XPCOMUtils.generateNSGetFactory( components );
} else {
    var NSGetModule = XPCOMUtils.generateNSGetModule( components );
}
